package com.xgp.microChat.controller;

import com.xgp.microChat.model.UploadFile;
import com.xgp.microChat.tool.DataGridView;
import org.bson.types.Binary;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;

/**
 * 文件上传
 */
@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Value("${server.port}")
    private int serverPort;

    @PostMapping("/uploadImage")
    public DataGridView<String> uploadImage(@RequestParam(value = "image") MultipartFile file){
        if(file.isEmpty())
            return new DataGridView<String>(false, "请选择一张图片", null);

        // 返回的 JSON 对象，这种类可自己封装
//        JSONResult jsonResult = null;
        String fileName = file.getOriginalFilename();
        try {
            UploadFile uploadFile = new UploadFile();
            uploadFile.setName(fileName);
            uploadFile.setCreatedTime(new Date());
            uploadFile.setContent(new Binary(file.getBytes()));
            uploadFile.setContentType(file.getContentType());
            uploadFile.setSize(file.getSize());

            UploadFile savedFile = mongoTemplate.save(uploadFile);
            String url = "http://localhost:" + serverPort + "/file/image/"+ savedFile.getId();
            return new DataGridView<String>(true, "图片上传成功!", url);
//            jsonResult =  JSONResult.build(200, "图片上传成功", url);
        } catch (IOException e) {
            e.printStackTrace();
            return new DataGridView<String>(false, "图片上传失败!", null);
//            jsonResult =  JSONResult.build(500, "图片上传失败", null);
        }
//        return jsonResult;
    }

    @GetMapping(value = "/image/{id}", produces = {MediaType.IMAGE_JPEG_VALUE, MediaType.IMAGE_PNG_VALUE})
    public byte[] image(@PathVariable String id){
        byte[] data = null;
        UploadFile file = mongoTemplate.findById(id, UploadFile.class);
        if(file != null){
            data = file.getContent().getData();
        }
        return data;
    }
}
